package com.androsz.ramdroidx;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class RAMDroidWidget extends AppWidgetProvider {

	public static final String ACTION_READY_TAP = "com.androsz.ramdroidx.READY_TAP";
	public static final String ACTION_START_UPDATE_RAM = "com.androsz.ramdroidx.START_UPDATE_RAM";
	public static final String ACTION_STOP_UPDATE_RAM = "com.androsz.ramdroidx.STOP_UPDATE_RAM";
	public static final String ACTION_UPDATE_RAM_ONCE = "com.androsz.ramdroidx.UPDATE_RAM_ONCE";

	@Override
	public void onReceive(final Context context, final Intent intent) {

		final String actionName = intent.getAction();
		if (!actionName.startsWith("com.androsz.ramdroidx")) {
			context.startService(new Intent(ACTION_READY_TAP, null, context, UpdateWidgetService.class));
			super.onReceive(context, intent);
			return;
		} else if (actionName.equals(AppWidgetManager.ACTION_APPWIDGET_DELETED)) {
			context.stopService(new Intent(context, UpdateWidgetService.class));
		}

		final SharedPreferences userPrefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		final String updateMethod = userPrefs.getString(context.getString(R.string.prefs_key_update_method), "");

		if (updateMethod.equals("Toggle")) {
			if (actionName.equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
				context.startService(new Intent(ACTION_READY_TAP, null, context, UpdateWidgetService.class));
			} else if (actionName.equals(ACTION_START_UPDATE_RAM)) {
				context.startService(new Intent(ACTION_START_UPDATE_RAM, null, context, UpdateWidgetService.class));
			} else if (actionName.equals(ACTION_STOP_UPDATE_RAM)) {
				context.stopService(new Intent(context, UpdateWidgetService.class));
			}
		} else if (updateMethod.equals("Tap")) {
			context.startService(new Intent(ACTION_UPDATE_RAM_ONCE, null, context, UpdateWidgetService.class));
		} else if (updateMethod.equals("Continuous")) {
			if (actionName.equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
				context.startService(new Intent(ACTION_START_UPDATE_RAM, null, context, UpdateWidgetService.class));
			}
		}
		super.onReceive(context, intent);
	}
}